import random
import string

import requests

from bs4 import BeautifulSoup
import subprocess
import re
import tempfile
import os
import time
import json

from utils.common import uuid_util


def get_ans_sn(url):
    """获取answer_session值"""
    resp = requests.get(url=url)
    answer_session = ''
    for cookie in resp.cookies:
        key = cookie.name
        val = cookie.value
        print(key, val)
        if key == 'answer_session':
            answer_session = val
    return answer_session


class TxExplain(object):

    def __init__(self, link):
        self.link = link
        self.json_explained_param = ""

    def get_initial_state_obj(self):
        # 假设response是包含HTML响应的字符串
        header = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36',
            'Referer': self.link
        }
        userid = str(uuid_util.uuid4())
        cookie_val = f'answer_session={get_ans_sn(self.link)}; __wj_userid={userid}'
        header['Cookie'] = cookie_val
        # link_arr = 'https://wj.qq.com/s2/12358376/1c14/'.split('/')
        link_arr = self.link.split('/')
        millisecond = int(round(time.time() * 1000))  # 生成13位时间戳
        new_link = 'https://wj.qq.com/api/v2/respondent/surveys/' + link_arr[4] + '/questions?_=' + str(millisecond) + '&hash=' + link_arr[5]
        response = requests.get(new_link, allow_redirects=False, headers=header, timeout=10)
        # 使用BeautifulSoup解析HTML
        content = response.content
        json_str = content.decode('utf-8')
        # meta信息，包含跳转规则
        meta_link = 'https://wj.qq.com/api/v2/respondent/surveys/' + link_arr[4] + '/meta?_=' + str(millisecond) + '&hash=' + link_arr[5]
        response4meta = requests.get(meta_link, allow_redirects=False, headers=header, timeout=10)
        content4meta = response4meta.content
        json_str4meta = content4meta.decode('utf-8')
        json_obj = json.loads(json_str)
        json_obj4meta = json.loads(json_str4meta)
        json_obj['data']['survey_rules'] = json.loads(json_obj4meta['data']['rule'])
        self.json_explained_param = json.dumps(json_obj)

    def convert_to_common_struct(self):
        # 原始数据字符串不能包含换行符“\n” 或者额外引号比如css样式style后的“，否则报错，需要提前去掉
        src_data = self.json_explained_param
        if not src_data:
            return ""
        src_data = src_data.replace('\n', '')
        src_data = re.sub(r'style=\".*?\"', '', src_data)
        current_dir = os.getcwd()
        js_file = current_dir + '/js_file/tx/retrieve2invoke.js'
        p = subprocess.Popen(['node', js_file, src_data], stdout=subprocess.PIPE)
        res = p.stdout.read().decode().strip()
        if not res:
            return ""
        return json.loads(res)

    def convert_to_common_struct2(self):
        # 原始数据字符串不能包含换行符“\n” 或者额外引号比如css样式style后的“，否则报错，需要提前去掉
        src_data = self.json_explained_param
        if not src_data:
            return ""
        src_data = src_data.replace('\n', '')
        src_data = re.sub(r'style=\".*?\"', '', src_data)
        # 保存 src_data 到临时文件
        with tempfile.NamedTemporaryFile(delete=False) as temp_file:
            temp_file.write(src_data.encode())
        # 执行 Node.js 脚本，并从临时文件中读取数据
        current_dir = os.getcwd()
        js_file = current_dir + '/js_file/tx/retrieve2invoke_v2.js'
        # js_file = 'D:/SrcCode/repo/code/git/question-be/js_file/tx/retrieve2invoke_v2.js'
        p = subprocess.Popen(['node', js_file, temp_file.name], stdout=subprocess.PIPE)
        res = p.stdout.read().decode().strip()
        # 删除临时文件
        temp_file.close()
        os.remove(temp_file.name)
        if not res:
            return ""
        return json.loads(res)

    def do_explain(self):
        self.get_initial_state_obj()
        return self.convert_to_common_struct2()
